<template>
  <el-container>
    <el-main class="main">
      <el-tooltip placement="left" style="text-align: center;margin: 0 auto 22px;">
        <div slot="content">封面上传</div>
        <el-upload
            class="avatar-uploader"
            action="api/Manage/Book/uploadBookCover"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="{
            'Authorization' : this.getToken
          }">
          <img v-if="book.bookImg !== ''" :src="book.bookImg | url">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

      </el-tooltip>
      <div class="from">
        <el-form label-position="left" label-width="80px" :model="book" ref="book" :rules="rules">
          <el-form-item label="书名" prop="bookName">
            <el-input v-model="book.bookName"></el-input>
          </el-form-item>
          <el-form-item label="作者" prop="bookAuthor">
            <el-input v-model="book.bookAuthor"></el-input>
          </el-form-item>
          <el-form-item label="字数">
            <el-input-number v-model="book.bookTotal" :min="0.01" :precision="2" label="字数"></el-input-number>
            万
          </el-form-item>

          <el-form-item label="类型" prop="type">
            <el-cascader
                v-model="book.type"
                :options="options"
                :props="{ expandTrigger: 'hover' }">

            </el-cascader>
          </el-form-item>
          <el-form-item label="状态">
            <el-row :gutter="10">
              <el-col :span="12">
                <el-switch
                    v-model="book.free"
                    active-text="免费"
                    inactive-text="付费">
                </el-switch>
              </el-col>
                <el-switch
                    v-model="book.full"
                    active-text="完本"
                    inactive-text="连载">
                </el-switch>
              <el-col :span="12">
              </el-col>
            </el-row>


          </el-form-item>
          <el-form-item label="">

          </el-form-item>

          <el-form-item label="简介" prop="bookIntroduce">
            <el-input
                type="textarea"
                :rows="5"
                placeholder="请输入内容"
                v-model="book.bookIntroduce">
            </el-input>
          </el-form-item>


        </el-form>
      </div>
      <el-upload
          class="novelUpload"
          drag
          action="api/Manage/Book/uploadBookFile"
          multiple
          :headers="{
            'Authorization' : this.getToken
          }"
          accept=".txt"
          :before-upload="beforeBookUpload"
          :on-success="handleBookSuccess"
      >
        <div v-if="book.bookPath===''" class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div v-else>
          <el-result icon="success" title="上传成功" :subTitle="book.bookPath"/>
        </div>
        <div class="el-upload__tip" slot="tip">只能上传txt文件，且不超过20MB</div>
      </el-upload>
    </el-main>
    <el-footer>
      <el-button type="primary" @click="onSubmit">提交</el-button>
      <el-button @click="closeDiaLog">取消</el-button>


    </el-footer>
  </el-container>
</template>

<script>

import {addBook, setBookByNumber} from "@/utils/api";

export default {
  name: "BookEditComponent.vue",
  props: {
    book:Object
  },
  data() {
    return {
      rules: {
        bookName: [
          { required: true, message: '请输入书名', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        bookAuthor: [
          { required: true, message: '请输入作者名', trigger: 'change' },
          { min: 1, max: 20, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        bookIntroduce:[
          { required: true, message: '请输入简介', trigger: 'change' },
          { min: 5, max: 250, message: '长度在 5 到 250 个字符', trigger: 'blur' }
        ],
        type :[
          { required: true, message: '请选择类型', trigger: 'change' },
        ]
      },
      options: [
        {
          value: '',
          label: '男频',
          children: [
              {
                value: '玄幻',
                label: '玄幻'
              }, {
                value: '武侠',
                label: '武侠'
              }, {
                value: '都市',
                label: '都市'
              }, {
                value: '游戏',
                label: '游戏'
              }, {
                value: '科幻',
                label: '科幻'
              }, {
                value: '悬疑',
                label: '悬疑'
              }
          ]

        }, {
          value: '',
          label: '女频',
          children: [
              {
                value: '古代言情',
                label: '古代言情'
              },  {
                value: '现代言情',
                label: '现代言情'
              },  {
                value: '玄幻言情',
                label: '玄幻言情'
              },  {
                value: '浪漫青春',
                label: '浪漫青春'
              },  {
                value: '现实生活',
                label: '现实生活'
              },  {
                value: '悬疑推理',
                label: '悬疑推理'
              }
          ]
        }
      ]
    }
  }, methods: {
    closeDiaLog(){
      this.resetForm("book")
      if(this.book.bookNumber === ''){
        this.$emit('addBookVisible',false)
      }else {
        this.$emit('dialogVisible',false)
      }
    },
    resetForm(formName) {
      // this.$refs[formName].resetFields();
    },
    onSubmit(){
      this.$refs['book'].validate((valid) => {
        if (valid) {
          if(this.book.type instanceof Array)
            this.book.type = this.book.type[1]
          if(this.book.bookNumber === ''){
            this.addBook()
          }else {
            this.updateBook()
          }
          this.closeDiaLog()
        } else {
          // console.log('error submit!!');

          return;
        }
      })


    },
    async updateBook(){
      setBookByNumber(this.book).then(res=>{
        if(res.code === 200){
          // console.log(res)
          this.notify("修改成功",this.book.bookName,"success")
          this.closeDiaLog()
        }else{
          this.notify("修改失败",this.book.bookName,"error")
          // console.error(res)
        }
      })
    },
    async addBook(){
      addBook(this.book).then(res=>{
        console.log(res)
        if(res.code === 200){

          this.notify("添加成功","","success")
          this.closeDiaLog()
        }else{
          this.notify("添加失败","","error")
          // console.error(res)
        }
      })
    },
    handleBookSuccess(res){
      console.log(res)
      this.book.bookPath = res.objects.replace('.txt','')
    },
    handleAvatarSuccess(res, file) {
      console.log(res)
      this.book.bookImg = res.objects
    },
    beforeBookUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 20;

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 20MB!');
      }
      return isLt2M;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },notify(msg,title,type) {
      this.$notify({
        title: title,
        message: msg,
        type: type
      });
    },
  }, watch: {}, computed: {
    getToken(){
      return localStorage.getItem("token")
    },
    getUser:{
      get(){
        return this.$store.getters.getUser;
      },
      set(value){
        return this.$store.commit("setUser",value);
      }
    },
  },filters:{

    url(value){
      return "api/"+value;
    }
  },mounted() {
  }
}
</script>

<style scoped>
.app{

}
.from{
  width: 500px;
  margin: 0;
  /*text-align: center;*/
  text-align: left;
}
.main{
  /*text-align: center;*/
  margin: 0 auto;
}
>>> .avatar-uploader  {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 180px;
  height: 240px;
}
>>>.avatar-uploader :hover {
  border-color: #409EFF;
}
>>>.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 240px;
  text-align: center;
}
>>>.el-upload__text{
  line-height: 242px;
}

>>>.novelUpload .el-upload-dragger{
  width: 340px;
  height: 242px;
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
</style>